package com.zoctan.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoctan.api.core.response.Result;
import com.zoctan.api.core.response.ResultGenerator;
import com.zoctan.api.model.Permission;
import com.zoctan.api.service.PermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Yangxiaokang
 * @date 2018/06/09
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Resource
    private PermissionService permissionService;

    @PreAuthorize("hasAuthority('role:list')")
    @GetMapping
    public Result listResourcePermission(@RequestParam(defaultValue = "0") final Integer page,
                                         @RequestParam(defaultValue = "0") final Integer size) {
        PageHelper.startPage(page, size);
        final List<com.zoctan.api.model.Resource> list = this.permissionService.findResourceWithHandle();
        final PageInfo<com.zoctan.api.model.Resource> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @PreAuthorize("hasAuthority('role:list')")
    @GetMapping("/list")
    public Result listPermission(@RequestParam(defaultValue = "0") final Integer page,
                                 @RequestParam(defaultValue = "0") final Integer size) {
        PageHelper.startPage(page, size);
        List<Permission> list = this.permissionService.findAll();
        final PageInfo<Permission> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @PreAuthorize("hasAuthority('perm:save')")
    @PostMapping("/save")
    public Result save(Permission p) {
        if(p.getId()!=null){
            permissionService.update(p);
        }else{
            permissionService.save(p);
        }
        return ResultGenerator.genOkResult("ok2");
    }

}
